package com.example.product.controller;

import com.example.product.feign.common.CommonResult;
import com.example.product.feign.RemoteProductService;
import com.example.product.feign.param.Price;
import com.example.product.service.IProductService;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

@RestController
public class ProductController implements RemoteProductService {

    @Resource
    private IProductService productService;

    /**
     * 默认线程池
     */
    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Override
    @GetMapping("/hello")
    public String hello() {
        return "hello world";
    }


    @PostMapping("/price")
    public CommonResult<Integer> price(@RequestBody List<Price> price){
        return CommonResult.success(productService.money(price));
    }

    @Override
    @PostMapping("/lock-stock")
    public CommonResult<Boolean> lockStock(@RequestBody  Price price) {
        return CommonResult.success(productService.lockStock(price));
    }



    /**
     * 使用线程池模拟并发测试
     *
     * @return {@link String}
     */
    @GetMapping("/test")
    public String test() {
        for (int i=0;i<100;i++){
            CompletableFuture.runAsync(()->{
                Price price = new Price();
                price.setProductId(1);
                Random random = new Random();
                int count = random.nextInt(5);
                while (count == 0){
                    count = random.nextInt(5);
                }
                price.setCount(count);
                this.lockStock(price);
            },threadPoolTaskExecutor);
        }
        System.out.println("执行完了");
        return "aa";
    }


}
